package filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class CheckLoginFilter
 */
@WebFilter("/*")
public class CheckLoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public CheckLoginFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		response.setContentType("text/html;charset=utf-8");
		HttpServletRequest req = (HttpServletRequest) request;
		String path = req.getServletPath();
		System.out.println("当前地址：" + path);
		if (path.equals("/studentLogin.jsp") || path.equals("/LoginServlet") || path.equals("/LoginOutServlet")) {
			chain.doFilter(req, response);// 放行
			return;
		}
		if (req.getSession().getAttribute("newsUser") == null) {
			PrintWriter out = response.getWriter();
			out.print("<script>alert('您没有登录，无权访问');location.replace('studentLogin.jsp');</script>");
			return;
		}
		chain.doFilter(req, response);// 放行

	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
